import { defineStore } from 'pinia'
import { ref } from 'vue'
import router from '../router'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const isLoading = ref(false)

  /**
   * 获取用户信息
   * @returns {Promise<Object|null>} 用户信息
   */
  const getUserInfo = async () => {
    if (!token.value) return null
    
    try {
      isLoading.value = true
      // 这里应该调用API获取用户信息
      // const response = await api.getUserInfo()
      // userInfo.value = response.data
      
      // 模拟API调用
      userInfo.value = {
        id: '1',
        username: 'admin',
        realName: '管理员',
        avatar: '',
        roles: ['admin'],
        permissions: ['*']
      }
      return userInfo.value
    } catch (error) {
      console.error('获取用户信息失败', error)
      return null
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 登录
   * @param {string} username 用户名
   * @param {string} password 密码
   * @returns {Promise<boolean>} 是否登录成功
   */
  const login = async (username, password) => {
    try {
      isLoading.value = true
      // 这里应该调用API进行登录
      // const response = await api.login({ username, password })
      // token.value = response.data.token
      
      // 模拟API调用
      token.value = 'mock-token-' + Date.now()
      localStorage.setItem('token', token.value)
      
      await getUserInfo()
      router.push('/')
      return true
    } catch (error) {
      console.error('登录失败', error)
      return false
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 登出
   */
  const logout = () => {
    token.value = ''
    userInfo.value = null
    localStorage.removeItem('token')
    router.push('/login')
  }

  /**
   * 检查是否已登录
   * @returns {boolean} 是否已登录
   */
  const isLoggedIn = () => {
    return !!token.value
  }

  return {
    token,
    userInfo,
    isLoading,
    getUserInfo,
    login,
    logout,
    isLoggedIn
  }
})